'use strict';

const path = require('path');
const Package = require('@test-hy-in/package');
const log = require('@test-hy-in/log');
const {exec:spawn} = require('@test-hy-in/utils');
// 将来有不同团队的话，通过这个配置文件实现不同init加载不同包
const SETTINGS  = {
    init:'@test-hy-in/init'
};

const CACHE_DIR = 'dependencies';

async function exec() {
    let targetPath = process.env.CLI_TARGET_PATH;
    const homePath = process.env.CLI_HOME_PATH;
    let storeDir = '';
    let pkg;
    log.verbose('targetPath:',targetPath)
    log.verbose('homePath:',homePath)
    const cmdObj = arguments[arguments.length-1];
    // 得到当前command的命令名称
    const cmdName = cmdObj.name();
    const packageName = SETTINGS[cmdName];
    // latest为最新包版本号
    const packageVersion = 'latest';

    if(!targetPath){
        console.log('不存在targetPath，生成默认')
        targetPath = path.resolve(homePath,CACHE_DIR);
        storeDir = path.resolve(targetPath,'node_modules');
        log.verbose('targetPath:',targetPath)
        log.verbose('storeDir:',storeDir)
        pkg = new Package({
            targetPath,
            packageName,
            storeDir,
            packageVersion
        });
        if(await pkg.exists()){
            // 更新packgae.json
            console.log('更新')
            await pkg.updata()
        }else{
            // 安装packgae.json
            console.log('安装')
            await pkg.install()
        }
    }else{
        console.log('存在targetPath')
        pkg = new Package({
            targetPath,
            packageName,
            packageVersion
        });
    }
    const rootFile = pkg.getRootFilePath();
    log.verbose('rootFile:',rootFile)
    if(rootFile){
        try{
            // 同步进程
            // require(rootFile).call(null,Array.from(arguments))
            // 多进程
            let args = Array.from(arguments);
            const cmd = args[args.length-1];
            const o = Object.create(null);
            Object.keys(cmd).forEach(key=>{
                if(cmd.hasOwnProperty(key) && !key.startsWith('_') && key!=='parent'){
                    o[key] = cmd[key]
                }
            });
            args[args.length - 1] = o;
            const code = `require('${rootFile}').call(null,${JSON.stringify(args)})`;
            const child = spawn('node',['-e',code],{
                cwd:process.cwd(),
                stdio:'inherit'
            });
            child.on('error',e=>{
                log.error(e.message)
                process.exit(1)
            });
            child.on('exit',e=>{
                log.verbose('命令执行成功：' + e)
                process.exit(e)
            });
        }catch(e){
            log.error(e.message)
        }
        
    }else{
        console.log('不存在rootFile')
    }
}



module.exports = exec;